package ActiveMQ.testHelloWorld;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by brossdong on 2017/12/15.
 */
public class TestSender {

    public static void main(String[] args) throws Exception {
        //1.建立ConnectionFactory工厂对象,需要填入用户名和密码,默认端口"tcp://localhost:61616"
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://localhost:61616");
        //2.通过ConnectionFactory工厂对象创建一个Connection对象,并用start开启连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        //3.通过ConnectionFactory工厂对象创建session会话,用于接收信息,参数配置1为是否开启事物,参数2为签收模式 , 一般设置为自动签收
        //Session session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);

        //通过事物
        //Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);

        //通过事物和client端接收方式
        Session session = connection.createSession(Boolean.TRUE, Session.CLIENT_ACKNOWLEDGE);

        //4.通过session创建destination,指的是一个客户端用来指定生产消息目标和消费信息来源的对象
        Queue destination = session.createQueue("queue1");
        //5.通过session创建消息的发送和接收对象(生产者和消费者)
        MessageProducer producer = session.createProducer(null);
        //6.可以通过MessageProducer的setDeverMode设置持久化和非持久化特性
        //producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        //7.用JMS规范TextMessage形式
        for (int i = 0; i < 5; i++) {
            TextMessage message = session.createTextMessage();
            message.setText("我是管儿子,id为" + i);
            //producer.send(message);
            //第一个参数:目的的
            //第二个参数:发送信息的内容
            //第三个参数:是否持久化
            //第四个参数:优先级(0-9  0-4普通5-9加急 默认为4)
            //第五个参数:消息存在mq上的时间
            producer.send(destination,message,DeliveryMode.NON_PERSISTENT,i,1000*60*2);
            System.out.println("生产者" + message.getText());
        }

        session.commit();

        if(connection != null) {
            connection.close();
        }

    }

}
